package edu.hwadee.BEIS.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import edu.hwadee.BEIS.constants.CustomException;
import edu.hwadee.BEIS.constants.ResultEnum;

public class DataUtil {

	/**
	 * 获取当前时间
	 * 
	 * @return
	 */
	public static Date getTime() {
		return new Date();
	}

	/**
	 * 获取n位随机数
	 * @param n
	 * @return
	 */
	public static String getRandom(int n) {
		String num = "";
		for (int i = 0; i < n; i++) {
			num = num + String.valueOf((int) Math.floor(Math.random() * 9 + 1));
		}
		return num;
	}

	/**
	 * SHA512加密
	 * @param str
	 * @return
	 */
	public static String SHA512(String str) {
		String res = null;

		if (str != null || str.length() > 0) {
			try {
				// 加密开始
				// 创建加密对象，并传入加密类型
				MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
				// 传入要加密的字符串
				messageDigest.update(str.getBytes());
				// 得到byte类型结果
				byte byteBuffer[] = messageDigest.digest();

				// 将byte转换为string
				StringBuffer strHexString = new StringBuffer();
				// 遍历byte buffer
				for (int i = 0; i < byteBuffer.length; i++) {
					String hex = Integer.toHexString(0xff & byteBuffer[i]);
					if (hex.length() == 1) {
						strHexString.append('0');
					}
					strHexString.append(hex);
				}
				// 得到返回结果
				res = strHexString.toString();
			} catch (NoSuchAlgorithmException e) {
				throw new CustomException(ResultEnum.PWD_SHA512);
			}
		}

		return res;
	}
	
	public static void main(String[] args) {
		System.out.print(SHA512(SHA512("123456")+"111111"));
	}
}
